package com.kzj.service.impl;

import com.kzj.domain.CourseSelectionInformation;
import com.kzj.dao.CourseSelectionInformationDao;
import com.kzj.global.constant.GlobalConstant;
import com.kzj.service.CourseSelectionInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kzj
 * @since 2023-12-01
 */
@Service
@Slf4j
public class CourseSelectionInformationServiceImpl extends ServiceImpl<CourseSelectionInformationDao, CourseSelectionInformation> implements CourseSelectionInformationService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public List<String> getCourseIdsByStudentIdAndTerm(String studentId, Integer term) {
        //TODO 是否做缓存呢?
        String key= GlobalConstant.SCHEDULE_STUDENT_ID_PREFIX+studentId+GlobalConstant.SCHEDULE_TERM_PREFIX+term;
        String s = stringRedisTemplate.opsForValue().get(key);
        if(s!=null){
            if(s.equals(""))
                return Collections.emptyList();
            System.out.println("查询缓存");
            String[] split = s.split(",");
            List<String> list= Arrays.asList(split);
            return list;
        }
        log.warn("查询数据库");
        List<CourseSelectionInformation> list = this.query().like("select_term", term)
                .eq("student_id", studentId).list();
        List<String> collect = list.stream().map(item -> item.getElectiveCourseId()).collect(Collectors.toList());
        String join= StringUtil.join(collect,",");
        stringRedisTemplate.opsForValue().set(key,join,GlobalConstant.SCHEDULE_TTL, TimeUnit.DAYS);
        return collect;
    }

    @Override
    public List<String> getStudentIdsByElectiveCourseId(String electiveCourseId) {
        List<CourseSelectionInformation> courseSelectionInformations = this.query().eq("elective_course_id",electiveCourseId).list();
        List<String> collect = courseSelectionInformations.stream().map(item -> item.getStudentId()).collect(Collectors.toList());
        return collect;
    }
}
